﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Reflection;
using System.Web;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Threading;

namespace MGGameWS
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MGGameService" in code, svc and config file together.
    [AspNetCompatibilityRequirements(
        RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MGGameService : IMGGameService
    {
        static ReaderWriterLock rwl = new ReaderWriterLock();
        private string TryToGetUserIPFromServerVariable(string varName)
        {
            string ipList = HttpContext.Current.Request.ServerVariables[varName];

            if (!string.IsNullOrEmpty(ipList))
            {
                return ipList.Split(',')[0];
            }

            return null;
        }

        private string GetUserIP()
        {
            var varArray = new string[] {
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR",
                "HTTP_X_FORWARDED",
                "HTTP_X_CLUSTER_CLIENT_IP",
                "HTTP_FORWARDED_FOR",
                "HTTP_FORWARDED",
                "REMOTE_ADDR"
            };

            foreach (var varName in varArray)
            {
                var ipAddress = TryToGetUserIPFromServerVariable(varName);
                if (!string.IsNullOrEmpty(ipAddress))
                {
                    return ipAddress;
                }
            }

            return null;
        }

        public void RecordData(Stream data)
        {

            var jsonReader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(data, new XmlDictionaryReaderQuotas());

            XElement root = XElement.Load(jsonReader);
      
            // The fields we'd like to extract
            XElement file = root.Element("file");
            XElement folder = root.Element("folder");
            XElement score = root.Element("score");
            XElement feulLevel = root.Element("feulLevel");
            XElement mc = root.Element("mechanicalCondition");
            XElement msgType = root.Element("msgType");
            XElement msgName = root.Element("msgName");
            XElement content = root.Element("content");
            var fileName = file.FirstNode;
            var folderName = folder.FirstNode;
            string filepath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            filepath = Path.GetDirectoryName(filepath) + "\\Experiment1\\assignmentId_" + folderName + "\\Game_";
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\staticInfo_" + fileName + ".txt";
            rwl.AcquireWriterLock(20000);
            var writer = new StreamWriter(filepath, true, Encoding.Unicode);
            var messageToWrite = "time: " + DateTime.Now
                + "\t" + "score: " + score.FirstNode
                + "\t" + "feulLevel: " + feulLevel.FirstNode
                + "\t" + "mechanicalCondition: " + mc.FirstNode
                + "\t" + "msgType: " + msgType.FirstNode + "\t" + "msgName: " + msgName.FirstNode + "\t" + "content: " + content.FirstNode;
            writer.Write(messageToWrite);
            writer.WriteLine();
            writer.Flush();
            writer.Close();
            rwl.ReleaseWriterLock();
        }

        public void FirstData(Stream data)
        {

            var jsonReader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(data, new XmlDictionaryReaderQuotas());

            XElement root = XElement.Load(jsonReader);

            // The fields we'd like to extract
            XElement file = root.Element("file");
            XElement folder = root.Element("folder");
            XElement assignmentId = root.Element("assignmentId");
            var fileName = file.FirstNode;
            var folderName = folder.FirstNode;
            string filepath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            filepath = Path.GetDirectoryName(filepath) + "\\Experiment1\\assignmentId_" + folderName + "\\Game_";
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\staticInfo_" + fileName + ".txt";

            var writer = new StreamWriter(filepath, true, Encoding.Unicode);

            var messageToWrite = "time: " + DateTime.Now
                + "\nworkerId: " + folderName
                + "\nhitId: " + fileName
                + "\nassignmentId: " + assignmentId.FirstNode;


            writer.Write(messageToWrite);
            writer.WriteLine();
            writer.Write("-----------------------------------------------------------------------------------------------");
            writer.WriteLine();
            writer.Flush();
            writer.Close();
        }

        public void HeaderData(Stream data)
        {

            var jsonReader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(data, new XmlDictionaryReaderQuotas());
            XElement root = XElement.Load(jsonReader);
            // The fields we'd like to extract
           
            XElement assignmentId = root.Element("assignmentId");
            XElement workerId = root.Element("workerId");
            XElement hitId = root.Element("hitId");
            XElement age = root.Element("age");
            XElement gender = root.Element("gender");
            XElement state = root.Element("state");
            XElement jobTitle = root.Element("jobTitle");
            XElement jobDesc = root.Element("jobDesc");
            XElement educationLevel = root.Element("educationLevel");
            XElement educationYears = root.Element("educationYears");
            XElement familyStatus = root.Element("familyStatus");
            XElement youBorn = root.Element("youBorn");
            XElement parentsBorn = root.Element("parentsBorn");


            var folderName = assignmentId.FirstNode;
            string filepath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            filepath = Path.GetDirectoryName(filepath) + "\\Experiment1\\assignmentId_" + folderName;
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\playerInfo";
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\demographic.txt";
            var writer = new StreamWriter(filepath, true, Encoding.Unicode);
            writer.Write("HEADER");
            writer.WriteLine();
            writer.WriteLine();
            var request = HttpContext.Current.Request;
            var messageToWrite = "Start time: " + DateTime.Now + "\n" +
                 "workerId: " + workerId.FirstNode + "\n" +
                  "hitId: " + hitId.FirstNode + "\n" +
                "assignmentId: " + assignmentId.FirstNode + "\n" +
                 "age: " + age.FirstNode + "\n" +
                 "gender: " + gender.FirstNode + "\n"+
                "state: " + state.FirstNode + "\n" +
                "job title: " + jobTitle.FirstNode + "\n" +
                "job description: " + jobDesc.FirstNode + "\n" +
                "education level: " + educationLevel.FirstNode + "\n" +
                "education years: " + educationYears.FirstNode + "\n" +
                "family status: " + familyStatus.FirstNode + "\n" +
                "you born: " + youBorn.FirstNode + "\n" +
                 "parents born: " + parentsBorn.FirstNode
                 + "\nIP address: " + GetUserIP()
                 + "\nOperating System: " + request.Browser.Platform
                + "\nBrowser: " + request.Browser.Browser;
            writer.Write(messageToWrite);
            writer.WriteLine();

            writer.Flush();
            writer.Close();


        }

        public void LastData(Stream data)
        {

            var jsonReader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(data, new XmlDictionaryReaderQuotas());

            XElement root = XElement.Load(jsonReader);

            // The fields we'd like to extract
            XElement file = root.Element("file");
            XElement folder = root.Element("folder");
            var fileName = file.FirstNode;
            var folderName = folder.FirstNode;
            string filepath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            filepath = Path.GetDirectoryName(filepath) + "\\Experiment1\\assignmentId_" + folderName;
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\playerInfo";
            if (!Directory.Exists(filepath))
                Directory.CreateDirectory(filepath);
            filepath = filepath + "\\behavior.txt";
            var writer = new StreamWriter(filepath, true, Encoding.Unicode);
            writer.Write("HEADER");
            writer.WriteLine();
            writer.WriteLine();
            var messageToWrite = "Start time: " + DateTime.Now + ";\n" +
"v01_gameStrategyDesc:" + root.Element("v01_gameStrategyDesc").FirstNode + "\n" +
         "v02_tendToSaveScore: " + root.Element("v02_tendToSaveScore").FirstNode + "\n" +
         "v03_fixIsBurden: " + root.Element("v03_fixIsBurden").FirstNode + "\n" +
         "v04_procrastinate: " + root.Element("v04_procrastinate").FirstNode + "\n" +
         "v05_knowRiskOfNotDoMntnce: " + root.Element("v05_knowRiskOfNotDoMntnce").FirstNode + "\n" +
         "v06_oldProductMntnce: " + root.Element("v06_oldProductMntnce").FirstNode + "\n" +
         "v07_readProspectForTimeMntnce: " + root.Element("v07_readProspectForTimeMntnce").FirstNode + "\n" +
         "v08_trustDiagnose: " + root.Element("v08_trustDiagnose").FirstNode + "\n" +
        "v09_scheduleAlertYourself: " + root.Element("v09_scheduleAlertYourself").FirstNode + "\n" +
        "v10_getAlertsAdvance: " + root.Element("v10_getAlertsAdvance").FirstNode + "\n" +
        "v11_turnOffAutoAlerts: " + root.Element("v11_turnOffAutoAlerts").FirstNode + "\n" +
         "v12_riskProneOrAverse: " + root.Element("v12_riskProneOrAverse").FirstNode + "\n" +
         "v13_usefulTool_Phone: " + root.Element("v13_usefulTool_Phone").FirstNode + "\n" +
         "v14_usefulTool_Email: " + root.Element("v14_usefulTool_Email").FirstNode + "\n" +
         "v15_usefulTool_Text_Message: " + root.Element("v15_usefulTool_Text_Message").FirstNode + "\n" +
         "v16_alertAreImportents: " + root.Element("v16_alertAreImportents").FirstNode + "\n" +
         "v17_careAboutMissedCalls: " + root.Element("v17_careAboutMissedCalls").FirstNode + "\n" +
         "v18_takeAlertsSeriously: " + root.Element("v18_takeAlertsSeriously").FirstNode + "\n" +
         "v19_differentMethosToContact: " + root.Element("v19_differentMethosToContact").FirstNode + "\n" +
         "v20_specificTimeToGetAlerts: " + root.Element("v20_specificTimeToGetAlerts").FirstNode + "\n" +
         "v21_callBackMissedCalls: " + root.Element("v21_callBackMissedCalls").FirstNode + "\n" +
      
            "v22_freeText:" + root.Element("v22_freeText").FirstNode;

            writer.Write(messageToWrite);
            writer.WriteLine();

            writer.Flush();
            writer.Close();

           
        }
    }
}
